from datetime import datetime
from app import db

class Robot(db.Model):
    """机器人数据模型"""
    __tablename__ = 'robots'
    
    id = db.Column(db.Integer, primary_key=True)
    robot_id = db.Column(db.String(50), unique=True, nullable=False, comment='机器人唯一标识')
    name = db.Column(db.String(100), nullable=False, comment='机器人名称')
    type = db.Column(db.String(20), nullable=False, comment='机器人类型：cleaning/transport/inspection/delivery')
    description = db.Column(db.Text, comment='机器人描述')
    ip_address = db.Column(db.String(50), comment='IP地址')
    port = db.Column(db.Integer, comment='端口号')
    protocol = db.Column(db.String(20), comment='通信协议')
    battery_capacity = db.Column(db.Integer, comment='电池容量(mAh)')
    max_load = db.Column(db.Float, comment='最大负载(kg)')
    move_speed = db.Column(db.Float, comment='移动速度(m/s)')
    status = db.Column(db.String(20), default='offline', nullable=False, comment='状态：online/offline/maintenance')
    last_active = db.Column(db.DateTime, default=datetime.utcnow, comment='最后活动时间')
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    def to_dict(self):
        """转换为字典，用于API返回"""
        return {
            'id': self.id,
            'robot_id': self.robot_id,
            'name': self.name,
            'type': self.type,
            'type_name': self.get_type_name(),
            'description': self.description,
            'ip_address': self.ip_address,
            'port': self.port,
            'protocol': self.protocol,
            'battery_capacity': self.battery_capacity,
            'max_load': self.max_load,
            'move_speed': self.move_speed,
            'status': self.status,
            'status_name': self.get_status_name(),
            'last_active': self.last_active.strftime('%Y-%m-%d %H:%M') if self.last_active else None,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M') if self.updated_at else None
        }
    
    def get_type_name(self):
        """获取机器人类型的中文名称"""
        type_mapping = {
            'cleaning': '清洁型',
            'transport': '搬运型',
            'inspection': '巡检型',
            'delivery': '配送型'
        }
        return type_mapping.get(self.type, self.type)
    
    def get_status_name(self):
        """获取状态的中文名称"""
        status_mapping = {
            'online': '在线',
            'offline': '离线',
            'maintenance': '维护中'
        }
        return status_mapping.get(self.status, self.status)

class Task(db.Model):
    """任务数据模型"""
    __tablename__ = 'tasks'
    
    id = db.Column(db.Integer, primary_key=True)
    robot_id = db.Column(db.Integer, db.ForeignKey('robots.id'), nullable=False, comment='关联的机器人ID')
    task_name = db.Column(db.String(100), nullable=False, comment='任务名称')
    progress = db.Column(db.Integer, default=0, comment='任务进度(0-100)')
    status = db.Column(db.String(20), default='pending', comment='任务状态：pending/running/completed/failed')
    created_at = db.Column(db.DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    # 关联机器人
    robot = db.relationship('Robot', backref=db.backref('tasks', lazy=True))
    
    def to_dict(self):
        """转换为字典，用于API返回"""
        return {
            'id': self.id,
            'robot_id': self.robot_id,
            'task_name': self.task_name,
            'progress': self.progress,
            'status': self.status,
            'status_name': self.get_status_name(),
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M') if self.updated_at else None
        }
    
    def get_status_name(self):
        """获取任务状态的中文名称"""
        status_mapping = {
            'pending': '待执行',
            'running': '运行中',
            'completed': '已完成',
            'failed': '已失败'
        }
        return status_mapping.get(self.status, self.status)
    